<template>
  <d-dialog
    ref="dialog"
    :header="'导入'"
    v-model:data="formData"
    v-model:visible="visible"
    :rules="rules"
    :width="600"
    :handleSubmit="handleSubmit"
  >
    <t-form-item label="选择导入文件" name="files" class="hideStar">
      <d-upload
        :sizeLimit="5000"
        accept=".xlsx,.xls"
        v-model="formData.files"
        tips="文件格式支持EXCEL，单个文件不大于500M"
        theme="file"
        :max="1"
        :multiple="true"
        class="w-100%"
        fileDir="files"
        @success="uploadSuccess"
        api="basic/guest/importExcel"
        :requestMethod="requestMethod"
      >
        <template #tips>
          <div>
            文件格式支持EXCEL，单个文件不大于500M
            <!-- <t-link
              hover="color"
              theme="primary"
              class="ml-16px"
              href="https://jdt-dev.oss-cn-shenzhen.aliyuncs.com/files/1716774025831_%E5%BA%8F%E5%88%97%E5%8F%B7%E6%A8%A1%E6%9D%BF.xlsx"
              download="序列号导入模板.xlsx"
              >下载模板</t-link
            > -->
          </div>
        </template>
      </d-upload>
    </t-form-item>
  </d-dialog>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import { merge, post } from '@common'
import { MessagePlugin } from 'tdesign-vue-next'
const emit = defineEmits(['upload-success'])
const INIT_STATUS = {
  files: null
}
const dialog = ref(null)
const visible = ref(false)
const formData = ref({ ...INIT_STATUS })
const uploadResultData = ref({})

const rules = {
  files: [{ required: true, message: '请上传文件', trigger: 'changeOrblur' }]
}

const handleSubmit = () => {
  const arr = uploadResultData.value.serialCodeList || []
  emit('upload-success', JSON.stringify(arr))
}
const uploadSuccess = (e) => {}
// 复写请求，覆盖组件原有请求
const requestMethod = async (file) => {
  const requestFile = file.raw || file?.[0].raw
  const uploadFormData = new FormData()
  uploadFormData.append('file', requestFile)
  const res = await post('basic/guest/importExcel', uploadFormData)
  if (res.code == 200) {
    MessagePlugin.success('上传成功')
  }
  uploadResultData.value = res.data
  return {
    status: 'success',
    response: {
      url: '',
      status: 'success',
      name: requestFile.name,
      size: requestFile.size,
      type: requestFile.type || (requestFile.name || '').split('.').pop()
    }
  }
}

const show = async (info = {}) => {
  uploadResultData.value = {}
  const obj = merge({ ...INIT_STATUS, isEdit: true }, info)
  formData.value = obj
  visible.value = true
}

defineExpose({ show })
</script>

<style lang="less">
.t-upload__dragger {
  width: 100%;
}
.hideStar {
  label {
    &::before {
      display: none;
    }
  }
}
</style>
